package com.hnx.admin.jwt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.hnx.admin.api.service.cache.CacheAPI;
import com.hnx.admin.redis.RedisCache;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Map;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/5/26   18:05:47 
描   述：
*/
@Component
@EnableConfigurationProperties(JwtProperties.class)
public record JwtUtil(JwtProperties  jwtProperties, RedisCache redisCache) implements CacheAPI {

    public  String createToken(Map<String,String> map) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(jwtProperties.getKey()));
        return token;
    }
    public DecodedJWT verifyToken(String token){
        try {
            JWTVerifier jwt = JWT.require(Algorithm.HMAC256(jwtProperties.getKey())).build();//生成验证对象
            return jwt.verify(token);
        }
        catch (Exception ex){
            return null;
        }
    }
    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(jwtProperties.getHeader());
        if (StringUtils.hasText(token) && token.startsWith(TOKEN_PREFIX))
        {
            token = token.replace(TOKEN_PREFIX, "");
        }
        return token;
    }
    public String getUserKey(HttpServletRequest request) {
        String token = getToken(request);
        if (org.springframework.util.StringUtils.hasText(token)) {
            DecodedJWT decodedJWT = verifyToken(token);
            String uuid = decodedJWT.getClaim("uuid").asString();
            return getTokenKey(uuid);
        }
        return null;
    }
    public String getUuid(HttpServletRequest request) {
        String token = getToken(request);
        if (org.springframework.util.StringUtils.hasText(token)) {
            DecodedJWT decodedJWT = verifyToken(token);
            return decodedJWT.getClaim("uuid").asString();
        }
        return null;
    }
}
